import React from 'react';
import { createForm } from 'rc-form';
import 'antd-mobile/dist/antd-mobile.css';
import Dropzone from 'react-dropzone';
import request from 'superagent';
import a from '../../img/a.png';

const data = [];

class ModifyImg extends React.Component {


    state = {
        files: data,
    }
    onChange = (files, type, index) => {
        console.log(files, type, index);
        this.setState({
            files,
        });
    }

    handleFileSelectOnDrop(files) {
        let file = files[0];
        this.state.showEmoticon = false;

        if (!this.state.filenames.hasOwnProperty(file.name)) {
            this.state.filenames[file.name] = false;
            let data = {
                name: file.name,
                preview: file.preview,
                attach_id: 0,
            };
            let key = this.state.files.push(data);
            key -= 1;
            this.setState(this.state);
            request
                .post(buildURL('file', 'upload'))
                .attach(file.name, file)
                .end((error, Response) => {
                    if (error || Response.status !== 200) {
                        this.state.Snackbar.open = true;
                        this.state.Snackbar.message = '上传失败！';
                        delete this.state.filenames[file.name];
                        delete this.state.files[key];

                    } else if (Response.body.status != 1) {
                        this.state.Snackbar.open = true;
                        this.state.Snackbar.message = Response.body.message;
                        delete this.state.filenames[file.name];
                        delete this.state.files[key];

                    } else if (Response.body.attach_id > 0) {
                        data.attach_id = Response.body.attach_id;
                        this.state.filenames[file.name] = true;

                    } else {
                        delete this.state.filenames[file.name];
                        delete this.state.files[key];
                    }
                    this.setState(this.state);
                });
        } else {
            this.state.Snackbar.open = true;
            this.state.Snackbar.message = '请勿重复选择照片！';
            this.setState(this.state);
        }
    }

    render() {
        const { files } = this.state;
        return (
            <Dropzone
                // style={styles.imagesSelectItem}
                onDrop={this.handleFileSelectOnDrop.bind(this)}
                accept={'image/*'}
                multiple={false}
            >
                <img src={a} />
            </Dropzone>
        );
    }
}

export default createForm()(ModifyImg);
